package me.zk.practice1.classloader;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author zhangkai
 * @date 2023/7/18 15:02
 */
public class PracticeClassLoader extends ClassLoader {

    private String path;

    public PracticeClassLoader(String path) {
        this.path = path;
    }
    public PracticeClassLoader(ClassLoader parent, String path) {
        super(parent);
        this.path = path;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        BufferedInputStream bis = null;
        ByteArrayOutputStream baos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(path + name+".class"));
            baos = new ByteArrayOutputStream();
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = bis.read(bytes))!=-1) {
                baos.write(bytes,0,len);
            }
            //获取内存中的完整的字节数组的数据
            byte[] classByteArray = baos.toByteArray();
            //将字节数组转换为Class的实例
            System.out.println("加载完毕！");
            return defineClass(null, classByteArray, 0, classByteArray.length);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != baos) {
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (null != bis) {
                    bis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        PracticeClassLoader myClassLoader = new PracticeClassLoader("/Users/zhangkai/Downloads/");
        Class<?> aClass = myClassLoader.loadClass("S1");
        System.out.println("对象:"+ aClass.newInstance());
        System.out.println("加载此类的类加载器为: " + aClass.getClassLoader());
        System.out.println("加载此类的类加载器的父类加载器为: " + aClass.getClassLoader().getParent().getClass().getName());

    }
}
